package com.pengcheng.hnweb.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.pengcheng.hnweb.job.TestJob;
import com.pengcheng.hnweb.service.DbService;
import com.pengcheng.hnweb.util.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

@Controller
public class IndexController {
    @Value("${remote.ip}")
    private String ip;
    @Value("${remote.port}")
    private int port;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RabbitUtil rabbitUtil;
    @Autowired
    private Common common;
    @Autowired
    private JsonUtil jsonUtil;
    @Autowired
    private DsendUtil dsendUtil;
    @Autowired
    private SocketUtil socketUtil;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private DbService dbService;
    @Autowired
    private TestJob testJob;
    @Autowired
    private ControllerUtil controllerUtil;
    @RequestMapping("/index")
    public String index( HttpServletRequest request,Model model)
    {
        model=controllerUtil.pre(request,model);
        return "index";
    }
    @RequestMapping("/")
    public String empty(HttpServletRequest request,Model model)
    {
        model=controllerUtil.pre(request,model);
        return "index";
    }
    @RequestMapping("/index_baidu")
    public String index_baidu(HttpServletRequest request,Model model)
    {
        model=controllerUtil.pre(request,model);
        return "index_baidu";
    }
    @RequestMapping("/resource")
    public String resource(HttpServletRequest request, Model model)
    {
        model=controllerUtil.pre(request,model);
        return "resource";
    }
    @RequestMapping("/site")
    public String site(HttpServletRequest request, Model model)
    {
        model=controllerUtil.pre(request,model);
        return "site";
    }
    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        request.getSession().removeAttribute("user_id");
        response.sendRedirect("/index");
        return "";
    }
    @RequestMapping("/{action}")
    public String list_user(HttpServletRequest request, Model model, @PathVariable("action") String action)
    {
        model=controllerUtil.pre(request,model);
        return action;
    }
    @RequestMapping("/refresh")
    @ResponseBody
    public Map<String, Object> refresh()
    {
        Map<String,Object> res=new HashMap<>();
        res.put("code",1);
        res.put("msg","success");
        return res;
    }
    @RequestMapping("/respon")
    @ResponseBody
    public String get_sn(@RequestParam("channel_id") String channel_id,@RequestParam("msg") String msg)
    {
        rabbitUtil.respon(channel_id,msg);
//        Map<String,Object> res=new HashMap<>();
//        res.put("channel_id",channel_id);
//        res.put("msg",msg);
//        rabbitTemplate.convertAndSend("hnww.respon",res);
        return "haha";
    }
    @RequestMapping("/msg")
    @ResponseBody
    public String msg(@RequestParam("channel_id") String channel_id,@RequestParam("msg") String msg)
    {
        Map<String,Object> res=new HashMap<>();
        res.put("channel_id",channel_id);
        res.put("msg",msg);
        res.put("type",1);
        rabbitTemplate.convertAndSend("hnww.msg",res);
        return "haha";
    }
    @RequestMapping("/test")
    @ResponseBody
    public String test() throws Exception
    {
        try {
            List<Map<String,Object>> column_dsendtask=dbService.columns("dsendtask");
            String sql="";
            sql="select * from hnww_dsendtask where id=5";
            List<Map<String,Object>> list_dsendtask=jdbcTemplate.queryForList(sql);
            list_dsendtask=dbService.get_dsendtask_detail(list_dsendtask);
            JSONArray rows_dsendtask=JSONArray.parseArray(JSONArray.toJSONString(list_dsendtask));
            for(int i=0;i<rows_dsendtask.size();i++)
            {
                JSONObject row_dsendtask=rows_dsendtask.getJSONObject(i);
                String msg=dsendUtil.get_msg(row_dsendtask);
                if(!common.is_empty(msg))
                {
                    socketUtil.send(msg);
                }
                //更新
                Map<String,Object> row=new HashMap<>();
                row.put("id",jsonUtil.get_int_by_path(row_dsendtask.toJSONString(),"$.id"));
                row.put("msg",msg);
                row.put("ip",ip);
                row.put("port",port);
                row.put("ftime",(int)(new Date().getTime()/1000));
                dbService.save(column_dsendtask,"dsendtask",row);
                return "msg:"+msg;
            }
            return "空";
        }
        catch (Exception ex)
        {
            fileUtil.add_msg("do_dsend",common.format_exception(ex));
            return ex.toString();
        }
    }
    @RequestMapping("/test_check")
    @ResponseBody
    public String test_check(@RequestParam("channel_id") int device_id,@RequestParam("msg") String type) throws Exception
    {
        String result="";
        try {
            int ftype=1;
            if(!type.equals("0"))
            {
                ftype=0;
            }
            //查询device
            String sql="select * from hnww_device where id=?";
            List<Map<String,Object>> rows_device=jdbcTemplate.queryForList(sql,device_id);
            //查询dlog
            sql="select * from hnww_dlog where device_id=? order by fdate desc limit 0,1";
            Object[] ps={device_id};
            List<Map<String,Object>> rows_dlog=jdbcTemplate.queryForList(sql,ps);

            Object[] ps1={ftype};
            sql="select * from hnww_alarmconfig where deleted=0 and for_site=1 and type=?";
            List<Map<String,Object>> rows_alarmconfig0=jdbcTemplate.queryForList(sql,ps1);
            sql="select * from hnww_alarmconfig where deleted=0 and for_resource=1 and type=?";
            List<Map<String,Object>> rows_alarmconfig1=jdbcTemplate.queryForList(sql,ps1);
            if(rows_device!=null&& rows_device.size()>0)
            {
                Map<String,Object> row_device=rows_device.get(0);
                List<Map<String,Object>> list_alarmconfig=new ArrayList<>();
                int dtype=Integer.parseInt(row_device.get("dtype").toString());
                int detail_id=Integer.parseInt(row_device.get("detail_id").toString());
                if(detail_id>0)
                {
                    if(dtype==0)
                    {
                        //用水单位
                        list_alarmconfig.addAll(rows_alarmconfig0);
                    }
                    else if(dtype==1)
                    {
                        list_alarmconfig.addAll(rows_alarmconfig1);
                    }
                }
                //查询所有alarmconfiglist里面device_id相关的alarmconfig
                sql="select * from hnww_alarmconfig where id in (select alarmconfig_id from hnww_alarmconfiglist where deleted=0 and device_id=?) and deleted=0 and type=?";
                Object[] ps2={device_id,ftype};
                List<Map<String,Object>> rows_alarmconfig=jdbcTemplate.queryForList(sql,ps2);
                list_alarmconfig.addAll(rows_alarmconfig);
                result+=("list_alarmconfig.length:"+list_alarmconfig.size());
                //查询所有已存在rows_alarm
                if(list_alarmconfig.size()>0)
                {
                    sql="select * from hnww_alarm where device_id="+device_id+" and alarmconfig_id in ";
                    String ids="";
                    for(int i=0;i< list_alarmconfig.size();i++)
                    {
                        if(!ids.equals(""))
                        {
                            ids+=",";
                        }
                        ids+=(list_alarmconfig.get(i).get("id").toString());
                    }
                    sql+=("("+ids+") and etime=0 and deleted=0");
                    List<Map<String,Object>> rows_alarm=jdbcTemplate.queryForList(sql);
                    result+=("rows_alarm.length:"+rows_alarm.size());
                    if(ftype==0)
                    {
                        //掉线告警
                        if(type.equals("1"))
                        {
                            result+=("设备上线");
                            //上线，把所有已存在的rows_alarm结束
                            for(int i=0;i<rows_alarm.size();i++)
                            {
                                sql="update hnww_alarm set etime=?,state=1 where id=?";
                                long etime=new Date().getTime();
                                Object[] ps4={etime,rows_alarm.get(i).get("id")};
                                jdbcTemplate.update(sql,ps4);
                                result+=("结束alarm:"+rows_alarm.get(i).get("id"));
                            }
                        }
                        else
                        {
                            //下线，循环list_alarmconfig，对于不存在alarm的新增alarm
                            for(int i=0;i< list_alarmconfig.size();i++)
                            {
                                int alarmconfig_id=Integer.parseInt(list_alarmconfig.get(i).get("id").toString());
                                int index=-1;
                                for(int j=0;j< rows_alarm.size();j++)
                                {
                                    if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                    {
                                        index=j;
                                        j=rows_alarm.size();
                                    }
                                }
                                if(index==-1)
                                {
                                    Map<String,Object> row=new HashMap<>();
                                    row.put("alarmconfig_id",alarmconfig_id);
                                    row.put("device_id",device_id);
                                    row.put("type",ftype);
                                    row.put("field","");
                                    row.put("ftime",(new Date().getTime()));
                                    row.put("etime",0);
                                    row.put("fval",0);
                                    row.put("state",0);
                                    row.put("deleted",0);
                                    List<Map<String,Object>> rows_column=dbService.columns("alarm");
                                    dbService.save(rows_column,"alarm",row);
                                    result+=("新增掉线alarm:"+device_id);
                                }
                            }
                        }
                    }
                    else
                    {
                        List<Map<String,Object>> rows_column=dbService.columns("alarm");
                        //判断当前最新dlog的参数，如果不存在alarm则新增，如果存在则更新
                        if(rows_dlog!=null&&rows_dlog.size()>0)
                        {
                            Map<String,Object> row_dlog=rows_dlog.get(0);
                            for(int i=0;i<list_alarmconfig.size();i++)
                            {
                                Map<String,Object> row_alarmconfig=list_alarmconfig.get(i);
                                int alarmconfig_id=Integer.parseInt(list_alarmconfig.get(i).get("id").toString());
                                BigDecimal sval=new BigDecimal(row_alarmconfig.get("sval").toString());
                                BigDecimal eval=new BigDecimal(row_alarmconfig.get("eval").toString());
                                String field=row_alarmconfig.get("field").toString();
                                BigDecimal fval=new BigDecimal(row_dlog.get(field).toString());
                                if(field.equals("flowrate")||field.equals("speed"))
                                {
                                    fval=fval.divide(new BigDecimal(1000));
                                }
                                if(fval.subtract(sval).doubleValue()>=0&&fval.subtract(eval).doubleValue()<=0)
                                {
                                    //告警存在
                                    int index=-1;
                                    for(int j=0;j< rows_alarm.size();j++)
                                    {
                                        if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                        {
                                            index=j;
                                            j=rows_alarm.size();
                                            Map<String,Object> row=new HashMap<>();
                                            row.put("id",rows_alarm.get(j).get("id").toString());
                                            row.put("fval",fval);
                                            dbService.save(rows_column,"alarm",row);
                                        }
                                    }
                                    if(index==-1)
                                    {
                                        Map<String,Object> row=new HashMap<>();
                                        row.put("alarmconfig_id",alarmconfig_id);
                                        row.put("device_id",device_id);
                                        row.put("type",ftype);
                                        row.put("field",field);
                                        row.put("ftime",(new Date().getTime()));
                                        row.put("etime",0);
                                        row.put("fval",0);
                                        row.put("state",0);
                                        row.put("deleted",0);
                                        dbService.save(rows_column,"alarm",row);
                                    }
                                }
                                else {
                                    //告警消失
                                    for(int j=0;j<rows_alarm.size();j++)
                                    {
                                        if(Integer.parseInt(rows_alarm.get(j).get("alarmconfig_id").toString())==alarmconfig_id)
                                        {
                                            sql = "update hnww_alarm set etime=?,state=1 where id=?";
                                            long etime = new Date().getTime();
                                            Object[] ps4 = {etime, rows_alarm.get(j).get("id").toString()};
                                            jdbcTemplate.update(sql, ps4);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            result+="end";
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            result+=ex.toString();
        }
        return result;
    }

    @RequestMapping("/test_weather")
    @ResponseBody
    public String test_weather()
    {
        testJob.get_tianqi();
        return "end";
    }

}
